package com.hkts.naturalgasauthentication.security;

import cn.hutool.core.util.StrUtil;
import com.hkts.naturalgasauthentication.base.dao.HontUserDao;
import com.hkts.naturalgasauthentication.base.entity.HontUser;
import com.hkts.naturalgasauthentication.base.service.HontUserService;
import com.hkts.naturalgasauthentication.common.Exception.AuttTionException;
import com.hkts.naturalgasauthentication.common.Exception.BlankException;
import com.hkts.naturalgasauthentication.common.Exception.LoginFailLimitException;
import com.hkts.naturalgasauthentication.security.jwt.JWTAuthenticationFilter;
import com.hkts.naturalgasauthentication.security.jwt.LoginFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private HontUserService hontUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        String loginType = LoginFilter.toThreadLocal.get();
        HontUser hontUserByUserName = null;
        if (loginType.equals("2")) {
            hontUserByUserName = hontUserService.findHontUserByUserName(s);
        } else {
            hontUserByUserName = hontUserService.findByMobile(s);
        }
        if(hontUserByUserName==null){
            throw new InternalAuthenticationServiceException("用户名或手机号不存在！");
        }
        if (hontUserByUserName.getApprove() == 0 || hontUserByUserName.getApprove() == 2) {
            throw new AuttTionException("请联系管理员进行认证！");
        } else if (hontUserByUserName.getStatus().equals("-1")) {
            throw new BlankException("已拉黑！");
        }
        String flagKey = "loginFailFlag:" + s;
        String value = redisTemplate.opsForValue().get(flagKey);
        Long timeRest = redisTemplate.getExpire(flagKey, TimeUnit.MINUTES);
        if (StrUtil.isNotBlank(value)) {
            //超过限制次数
            throw new LoginFailLimitException("登录错误次数超过限制，请" + timeRest + "分钟后再试");
        }
        return new SecurityUserDetails(hontUserByUserName);
    }
}
